package com.zyc.fuckfx.apk;

import com.zyc.fuckfx.base.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashUtil {
    /**
     * 通过检查签名文件classes.dex文件的哈希值来判断代码文件是否被篡改
     *
     * @param orginalSHA 原始Apk包的SHA-1值
     */
    public static void apkVerifyWithSHA(String apkPath,String orginalSHA) {
        orginalSHA = "zqUnl2/WM1U/aNl9Wp6UmDbqmyS7NvO4yPntbrPH4pc=";

        //sh1 445725068d17a4704ab92883fda05a7b8ddb9728
        //sh256 cea527976fd633553f68d97d5a9e949836ea9b24bb36f3b8c8f9ed6eb3c7e297
        try {
            MessageDigest dexDigest = MessageDigest.getInstance("SHA-1");
            byte[] bytes = new byte[1024];
            int byteCount;
            FileInputStream fis = new FileInputStream(apkPath); // 读取apk文件
            while ((byteCount = fis.read(bytes)) != -1) {
                dexDigest.update(bytes, 0, byteCount);
            }
            BigInteger bigInteger = new BigInteger(1, dexDigest.digest()); // 计算apk文件的哈希值
            String sha = bigInteger.toString(16);
            fis.close();
            Log.i("sha =" +sha);
            if (sha.equals(orginalSHA)) { // 将得到的哈希值与原始的哈希值进行比较校验
                Log.i("验证成功");
            }else {
                Log.i("验证失败");
            }
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
    }
}
